package com.baby.movie.app.ui;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.baby.movie.R;
import com.baby.movie.model.Video;
import com.baby.movie.model.response.VideosResponse;
import com.baby.movie.service.MTService;
import com.baby.movie.util.AppUtil;
import com.baby.movie.util.Constants;
import com.baby.movie.widget.SlideShowAdapter;
import com.common.util.AndroidUtil;
import com.common.util.JsonUtil;
import com.common.util.Logs;
import com.common.view.ViewHolder;
import com.common.widget.RefreshListView;
import com.common.widget.SlideShow;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.TextHttpResponseHandler;
import com.viewpagerindicator.CirclePageIndicator;

public class MTFragment extends BaseFragment {
	
	private static final int START_PAGE = 1;
	
	private RefreshListView mListView;
	
	private SlideShow mSlideShow;
	
	private CirclePageIndicator mIndicator;
	
	private SlideShowAdapter mGalleryAdapter;
	
	private TextView mTvMore;
	
	private int mPage;
	
	private List<List<Video>> mVideos;
	
	private MTAdapter mAdapter;
	
	private int mDataCount;

	private View header;
	
	@Override
	protected int getContentViewRes() {
		return R.layout.fragment_mt;
	}

	@Override
	protected void findViews(View contentView) {
		mListView = (RefreshListView) contentView.findViewById(R.id.mListView);
	}

	@Override
	protected void initialize() {
		header = mInflater.inflate(R.layout.header_slideshow, null);
		mSlideShow = (SlideShow) header.findViewById(R.id.slideShow);
		mIndicator = (CirclePageIndicator) header.findViewById(R.id.indicator);
		mTvMore = (TextView) header.findViewById(R.id.tvMore);
		mTvMore.setText("更多");
		mTvMore.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showMore();
			}
		});
		
		mGalleryAdapter = new SlideShowAdapter(mContext);
		mSlideShow.setAdapter(mGalleryAdapter);
		
		
		mListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				refreshData();
			}
		});
		
		mVProgress.setTextClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				refreshData();
			}
		});
		
		refreshData();
	}
	
	private void showMore() {
		Intent intent = new Intent(mContext, MoreMTDetailActivity.class);
		startActivity(intent);
	}
	
	private OnLastItemVisibleListener mOnLastItemVisibleListener = new OnLastItemVisibleListener() {

		@Override
		public void onLastItemVisible() {
			getVideos(mPage);
		}
	};
	
	private void refreshData() {
		getVideos(START_PAGE);
	}
	
	private class MTAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return null == mVideos ? 0 : mVideos.size();
		}

		@Override
		public List<Video> getItem(int position) {
			return mVideos.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ItemHolder holder = null;
			if (null == convertView) {
				convertView = mInflater.inflate(R.layout.item_mt, null);
				View leftView = convertView.findViewById(R.id.left);
				View rightView = convertView.findViewById(R.id.right);
				
				holder = new ItemHolder();
				holder.left = new MTHolder(leftView);
				holder.right = new MTHolder(rightView);
				convertView.setTag(holder);
			} else {
				holder = (ItemHolder) convertView.getTag();
			}
			
			List<Video> videos = getItem(position);
			holder.left.setData(videos.get(0));
			Video video = null;
			if (videos.size() > 1) {
				video = videos.get(1);
			}
			holder.right.setData(video);
			
			
			return convertView;
		}
		
	}
	
	private class ItemHolder {
		MTHolder left, right;
	}
	
	private class MTHolder extends ViewHolder<Video> {
		
		View vItem;
		
		ImageView ivImage;
		
		TextView tvTitle, tvSummary;

		public MTHolder(View convertView) {
			super(convertView);
			vItem = convertView.findViewById(R.id.vItem);
			ivImage = (ImageView) convertView.findViewById(R.id.ivImage);
			tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
			tvSummary = (TextView) convertView.findViewById(R.id.tvSummary);
		}

		@Override
		public void setData(Video d) {
			if (null == d) {
				mConvertView.setVisibility(View.GONE);
				return;
			} else {
				mConvertView.setVisibility(View.VISIBLE);
			}
			loadImage(d.Cover, ivImage);
			tvTitle.setText(d.Title);
			tvSummary.setText(d.Summary);
			
			vItem.setTag(d);
			vItem.setOnClickListener(mMtClickListener);
		}
	}
	
	private OnClickListener mMtClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			Video video = (Video) v.getTag();
			AppUtil.showMtDetail(mContext, video);
		}
	};
	
	private void addGallery(List<Video> datas) {
		List<Video> videos = new ArrayList<Video>();
		for (Video video : datas) {
			if (!AndroidUtil.isEmpty(video.Cover)) {
				videos.add(video);
			}
		}
		if (null == mAdapter) {
			mListView.getRefreshableView().addHeaderView(header);
			
			mAdapter = new MTAdapter();
			mListView.setAdapter(mAdapter);
		}
		
		mGalleryAdapter.setData(videos);
		mGalleryAdapter.notifyDataSetChanged();
		mIndicator.setViewPager(mSlideShow);
	}
	
	private RequestHandle mRequestHandle;
	private void getVideos(final int page) {
		TextHttpResponseHandler responseHandler = new TextHttpResponseHandler() {
			
			@Override
			public void onStart() {
				super.onStart();
				if (null == mAdapter || mAdapter.isEmpty()) {
					showProgress();
				} else {
					mListView.showFooter();
				}
			}
			
			@Override
			public void onFinish() {
				super.onFinish();
				hideProgress();
				mListView.hideFooter();
				mListView.onRefreshComplete();
			}
			
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String responseString) {
				Logs.v(responseString);
				try {
					VideosResponse response = JsonUtil.fromJson(responseString, VideosResponse.class);
					List<Video> data = response.Data;
					if (!AndroidUtil.isEmpty(data)) {
						List<List<Video>> datas = parseData(data);
						if (page == START_PAGE) {
							mDataCount = 0;
							mVideos = datas;
							// TODO test add gallery
							addGallery(data);
						} else {
							mVideos.addAll(datas);
						}
						
						mAdapter.notifyDataSetChanged();
						mDataCount += data.size();
						mPage = page + 1;
						if (mDataCount >= response.Total) {
							mListView.removeLastVisibleListener();
						} else if (null != mListView.getLastItemVisibleListener()) {
							mListView.setOnLastItemVisibleListener(mOnLastItemVisibleListener);
						}
					}
				} catch (Exception e) {
					toast("Fail");
				}
			}
			
			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				toast("Fail");
			}
		};
		
		mRequestHandle = MTService.getVideoAll(page, responseHandler);
	}
	
	private List<List<Video>> parseData(List<Video> videos) {
		List<List<Video>> datas = new ArrayList<List<Video>>();
		List<Video> data = null;
		for (int i = 0, len = videos.size(); i < len; i++) {
			if (i % 2 == 0) {
				data = new ArrayList<Video>();
				datas.add(data);
			}
			data.add(videos.get(i));
		}
		return datas;
	}
	
	@Override
	public void onDestroy() {
		MTService.cancel(mRequestHandle);
		
		super.onDestroy();
	}

}
